from django.shortcuts import render

from  rest_framework.views import  APIView
from  rest_framework.response import Response
from django.core.paginator import Paginator
from .models import User,Goods,Order
from .serializer import UserSerializer,GoodsSerializer,OrderSerializer,ShowOrderSerializer



class Login(APIView):
    def post(self,request):
        username=request.data.get("username")
        password=request.data.get("password")
        user_obj=User.objects.filter(username=username,password=password).first()
        print(user_obj)
        if user_obj:
            return  Response({"msg":"ok","code":200,"token":user_obj.id,"username":user_obj.username,'fen':user_obj.fen})
        else:
            return Response({"msg":"用户或密码错误"})

    def get(self,request):
        current_page=request.query_params.get("page",1)
        goods_obj=Goods.objects.all()
        paginator=Paginator(goods_obj,1)
        paged=paginator.page(current_page)
        goods_serializer=GoodsSerializer(paged,many=True)
        return Response({
            "data":goods_serializer.data,
            "page_list":[i for i in paginator.page_range],
            "page_sum":paginator.num_pages
        })

class OrderAPIView(APIView):
    def post(self,request):
        user=request.data.get("user")
        goods=request.data.get("goods")
        goods_obj=Order.objects.filter(user_id=user,goods_id=goods).first()
        if goods_obj:
            goods_obj.number += 1
            goods_obj.save()
            user_obj = User.objects.filter(pk=user).first()
            goods = Goods.objects.filter(pk=goods).first()
            if user_obj:
                user_obj.fen += goods.goods_price * 0.1
                user_obj.save()
            return Response({"msg":"下单成功","code":200})
        else:
            order_ser = OrderSerializer(data=request.data)
            if order_ser.is_valid():
                order_ser.save()
                user_obj = User.objects.filter(pk=user).first()
                goods = Goods.objects.filter(pk=goods).first()
                if user_obj:
                    user_obj.fen += goods.goods_price * 0.1
                    user_obj.save()
                return Response({"msg":"下单成功","code":200})
    def get(self,request):
        user=request.query_params.get("user")
        order_list=Order.objects.filter(user=user)
        order_serializer=ShowOrderSerializer(order_list,many=True)
        return Response({"code":200,"data":order_serializer.data})